#ifndef RINGBUFFER_H
#define RINGBUFFER_H
#include <QVector>
#include <QtGlobal>

#define DEBUG (1)

namespace UartNamespace {
class CharRingBuffer {
public:
    explicit CharRingBuffer(int size) : buffer(size), head(0), tail(0), maxSize(size), count(0) {}

    bool write(const char* data, int dataSize) {
      if (count >= maxSize) {
        return false;
      }

      for (int i = 0; i < dataSize; ++i) {
        buffer[tail] = data[i];
#if DEBUG
        qDebug() << "write:" << data[i];
#endif
        tail = (tail + 1) % maxSize;
        ++count;
      }

      return true;
    }

    bool read(char* data, int& dataSize) {
      if (count == 0) {
        return false;
      }

      int i;
      for (i = 0; i < dataSize && count > 0; ++i) {
        data[i] = buffer[head];
#if DEBUG
        qDebug() << "read:" << data[i];
#endif
        head = (head + 1) % maxSize;
        --count;
      }

      dataSize = i; // 更新实际读取的数据量
      return true;
    }

    bool isEmpty() const {
      return count == 0;
    }

    bool isFull() const {
      return count == maxSize;
    }

    int size() const {
      return count;
    }

private:
    QVector<char> buffer;
    int head; // 缓冲区的头部索引
    int tail; // 缓冲区的尾部索引
    int maxSize; // 缓冲区的最大大小
    int count; // 缓冲区当前存储的数据量
};
}
#endif // RINGBUFFER_H

